/*
* 新购物车页面
* */
import React, {Component} from 'react';
import {
    View,
    Text,
    Image,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    TextInput,
    ActivityIndicator,
    DeviceEventEmitter
} from 'react-native';
import Util from '../common/util'
import * as URLconstant from '../constant/URLconstant'
import MyStroage from "../common/myStroage";
import Header from '../common/header';
import Icon from 'react-native-vector-icons/FontAwesome'
import Toast from '../common/ToastUtil';
import ConfirmOrder from '../order/confirmOrder'

export default class newShoppingCart extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            user_id: '',
            loaded: true,
            goodsList: [],
            isAllSelect: false,
            selectNum: 0,
            selectGoods: [],
            settlePrice: 0,
            isEdit: 0
        };
        this.editCart = this.editCart.bind(this)
    }

    componentDidMount() {
        this.getUser()
        this.addCartListener()
    }


    //监听更改购物车(加入购物车和下单)
    addCartListener(){
        DeviceEventEmitter.addListener('changeCart',()=>{
            this.getUser()
        })
    }

    async getUser() {
        try {
            let userInfoDate = await MyStroage.getStorageAllDataForKey('userinfo')
            if (userInfoDate) {
                this.getCart(userInfoDate.data.user_id)
            }
        } catch (err) {
            LOG(err);
        }
    }

    getCart(user_id) {
        if (user_id) {
            this.setState({
                user_id: user_id
            })
        } else {
            user_id = this.state.user_id
        }
        let url = URLconstant.NEW_CART_URL
        let datakey = []
        datakey['user_id'] = user_id
        Util.get(url, datakey, this.getCartSuc.bind(this), this.errorCallback.bind(this))
    }

    async getCartSuc(datas) {
        if (datas.status == 0) {
            let goodsList = []
            let data = datas.data.goods_list.goods
            if (data) {
                goodsList = data
            }
            for (let item of goodsList) {
                item.is_select = false
            }
            this.setState({
                goodsList: goodsList,
                loaded: false,
                selectGoods: [],
                selectNum: 0,
                settlePrice: 0,
                isAllSelect: false
            })
        }
    }

    errorCallback(err) {

    }

    toGoodsIndex(goods_id) {
        this.props.navigation.push('GoodsIndex', {
            goods_id: goods_id
        })
    }


    toFixedNum(num) {
        return parseFloat(num).toFixed(2)
    }

    //去结算
    toSettle() {
        let user_id = this.state.user_id
        let list = this.state.selectGoods.toString()
        this.props.navigation.push('ConfirmOrder',{
            list:list,
            user_id:user_id,
            type:1
        })
    }

    //删除购物车某个商品
    deleteGoods(selectGoods) {
        if (selectGoods == undefined) {
            selectGoods = this.state.selectGoods
        }
        if (selectGoods.length == 0) {
            Toast.show('删除成功')
            this.setState({
                isEdit: 0
            })
            this.getCart()
            return false
        }

        let url = URLconstant.DELETECART_URL
        let datakey = []
        datakey['user_id'] = this.state.user_id;
        datakey['shopping_id'] = selectGoods[0];
        Util.post(url, datakey, (datas) => {
            if (datas.status == 0) {
                selectGoods.splice(0, 1)
                this.deleteGoods(selectGoods)
            }
        }, this.errorCallback.bind(this))
    }

    backPriceTxt(txt) {
        return txt.split('*')[0]
    }

    //勾选商品
    selectGoods(shopping_id) {
        let goodsList = this.state.goodsList
        for (let item of goodsList) {
            if (item.shopping_id == shopping_id) {
                LOG('aaaa')
                item.is_select = !item.is_select
            }
        }
        this.setState({
            goodsList: goodsList
        })
        this.getSelectGoods(goodsList)
        this.getIsAllSelect(goodsList)
    }

    //获取勾选商品的信息
    getSelectGoods(goodsList) {
        let selectNum = 0
        let selectGoods = []
        let settlePrice = 0
        for (let item of goodsList) {
            if (item.is_select == true) {
                selectNum++
                selectGoods.push(item.shopping_id)
                settlePrice += item.buy_price * item.quantity
            }
        }
        this.setState({
            selectNum: selectNum,
            selectGoods: selectGoods,
            settlePrice: settlePrice.toFixed(2)
        })
    }

    //获取是否全选
    getIsAllSelect(goodsList) {
        let isAllSelect = true
        for (let item of goodsList) {
            if (!item.is_select) {
                isAllSelect = false
                break;
            }
        }
        this.setState({
            isAllSelect: isAllSelect
        })
    }

    //全选商品
    selectAll() {
        let goodsList = this.state.goodsList
        let isAllSelect = this.state.isAllSelect
        for (let item of goodsList) {
            item.is_select = !isAllSelect
        }
        this.setState({
            goodsList: goodsList,
            isAllSelect: !isAllSelect
        })
        this.getSelectGoods(goodsList)
    }


    showGoods() {
        let goodsList = this.state.goodsList
        return (
            <View>
                {
                    goodsList.map((item, index) => {
                        return (
                            <View key={index} style={styles.goods_item}>
                                <TouchableOpacity onPress={() => this.selectGoods(item.shopping_id)}
                                                  style={styles.goods_select_view}>
                                    {
                                        item.is_select ?
                                            <Icon name={"check-circle"} size={25} color={'#ee1f12'}/>
                                            :
                                            <Icon name={'circle-o'} size={25} color={'#ccc'}/>
                                    }
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this.toGoodsIndex(item.goods_id)}
                                                  style={styles.goods_item_right}>
                                    <Image
                                        source={{uri: item.goods_img}}
                                        resizeMode={'cover'}
                                        style={{width: 90, height: 90}}
                                    />
                                    <View style={styles.goods_info_view}>
                                        <Text numberOfLines={2}
                                              style={{fontSize: 14, color: "#000"}}>{item.goods_name}</Text>
                                        <Text style={{fontSize: 12, color: "#969696"}}>{item.shop_name || '平台总'}仓
                                            ({item.stock}{item.is_means == 1 ? '箱' : '支'})</Text>
                                        <Text style={{fontSize: 12, color: "#969696"}}>{item.specification}</Text>
                                        <View style={{
                                            flexDirection: 'row',
                                            alignItems: 'center',
                                            justifyContent: 'space-between'
                                        }}>
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#ee1f12"
                                            }}>会员专享:{this.toFixedNum(item.metre_price)}元/米</Text>
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#ee1f12"
                                            }}>{item.quantity}{item.is_means == 1 ? '箱' : '支'}</Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        )
                    })
                }
            </View>
        )
    }


    showSettlement() {
        let selectNum = this.state.selectNum
        let isEdit = this.state.isEdit
        return (
            <View style={styles.settle_view}>
                <TouchableOpacity onPress={() => this.selectAll()}
                                  style={{flexDirection: 'row', alignItems: "center", justifyContent: "center"}}>
                    {
                        this.state.isAllSelect ?
                            <Icon name={"check-circle"} size={25} color={'#ee1f12'}/>
                            :
                            <Icon name={'circle-o'} size={25} color={'#ccc'}/>
                    }
                    <Text style={{fontSize: 12, color: "#696969", marginLeft: 5}}>全选</Text>
                </TouchableOpacity>
                {
                    isEdit == 0 ?
                        <View>
                            {
                                selectNum == 0 ?
                                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                        <View style={styles.normal_btn}>
                                            <Text style={{fontSize: 14, color: "#fff"}}>结算</Text>
                                        </View>
                                    </View> :
                                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                            <Text style={{fontSize: 12, color: "#696969"}}>合计:</Text>
                                            <Text style={{
                                                fontSize: 16,
                                                color: "#ee1f12",
                                                marginLeft: 5
                                            }}>¥{this.state.settlePrice}</Text>
                                        </View>
                                        <TouchableOpacity onPress={() => this.toSettle()} style={styles.settle_btn}>
                                            <Text style={{fontSize: 14, color: "#fff"}}>结算({selectNum})</Text>
                                        </TouchableOpacity>
                                    </View>
                            }
                        </View> :
                        <View>
                            {
                                selectNum == 0 ?
                                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                        <View style={styles.normal_btn}>
                                            <Text style={{fontSize: 14, color: "#fff"}}>删除</Text>
                                        </View>
                                    </View> :
                                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                        <TouchableOpacity onPress={() => this.deleteGoods()} style={styles.settle_btn}>
                                            <Text style={{fontSize: 14, color: "#fff"}}>删除({selectNum})</Text>
                                        </TouchableOpacity>
                                    </View>
                            }
                        </View>
                }

            </View>
        )
    }


    editCart() {
        let isEdit = this.state.isEdit
        isEdit = isEdit == 0 ? 1 : 0
        this.setState({
            isEdit: isEdit
        })
    }


    backHome(){
        this.props.navigation.navigate('Home')
    }

    render() {
        let goodsList = this.state.goodsList
        return (
            <View style={{flex: 1, backgroundColor: "#fff"}}>
                <Header navigation={this.props.navigation} title={'购物车'} hideBack={true}/>
                {
                    this.state.loaded ?
                        <View style={{flex: 1,}}>
                            {Util.loading()}
                        </View> :
                        <View style={{flex: 1}}>
                            {
                                goodsList.length == 0 ?
                                    <ScrollView style={{flex: 1}}>
                                        <View style={{
                                            height: Util.size.height - 200,
                                            alignItems: 'center',
                                            justifyContent: 'center'
                                        }}>
                                            <Image
                                                source={require('../imgs/u1006.png')}
                                                resizeMode={'cover'}
                                                style={{width: 227, height: 174, marginBottom: 50}}
                                            />
                                            <TouchableOpacity onPress={() => this.backHome()} style={{
                                                width: 200,
                                                height: 40,
                                                borderRadius: 5,
                                                backgroundColor: "#ee1f12",
                                                alignItems: 'center',
                                                justifyContent: 'center'
                                            }}>
                                                <Text style={{fontSize: 14, color: "#fff"}}>再去逛逛</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </ScrollView>
                                    :
                                    <View style={{flex: 1}}>
                                        <ScrollView style={{flex: 1}}>
                                            {this.showGoods()}
                                        </ScrollView>
                                        {this.showSettlement()}
                                    </View>
                            }

                        </View>
                }
            </View>
        )
    }
}
var styles = StyleSheet.create({
    goods_item: {
        paddingVertical: 15,
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: "#f0f0f0",
        flexDirection: "row",
        alignItems: 'center'
    },
    goods_select_view: {
        width: 40,
        height: 40,
        alignItems: 'center',
        justifyContent: 'center'
    },
    goods_item_right: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center'
    },
    goods_info_view: {
        flex: 1,
        paddingLeft: 10,
        height: 90,
        justifyContent: 'space-between'
    },
    settle_view: {
        height: 50,
        backgroundColor: "#f2f2f2",
        paddingLeft: 15,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: 'space-between'
    },
    settle_btn: {
        width: 100,
        height: 50,
        backgroundColor: "#ee1f12",
        alignItems: 'center',
        justifyContent: 'center',
        marginLeft: 10
    },
    normal_btn: {
        width: 100,
        height: 50,
        backgroundColor: "#aaa",
        alignItems: 'center',
        justifyContent: 'center',
        marginLeft: 10
    }
})